package com.sunyard.pcc.shiro.core;

import com.sunyard.pcc.common.bo.SysUserBO;
import com.sunyard.pcc.common.constant.ErrorCodeEnum;
import com.sunyard.pcc.common.constant.UserStatusEnum;
import com.sunyard.pcc.common.exception.PccCommonException;
import com.sunyard.pcc.core.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: Hewei
 * @Description: 自定义用户校验类
 * @Date: Created in 17:37 2018/2/8
 */
@Slf4j
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        log.info("shiro 登陆认证");
        //获取用户输入的账号
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String telephone = (String)token.getPrincipal();

        SysUserBO sysUserBO;
        try {
            sysUserBO = userService.selectUserByTelephone(telephone);
        } catch (PccCommonException e){
            log.error(e.toString());
            // TODO: 2018/4/10 改变error类型
            throw new AuthenticationException(ErrorCodeEnum.HAVE_NOT_LOGIN.getErrorMsg());
        }

        if (sysUserBO == null) {
            log.info("用户名对应用户不存在");
            throw new UnknownAccountException(ErrorCodeEnum.USER_DO_NOT_EXITS.getErrorMsg());
        }

        //改为由用户的登录失败次数处校验
//        else if (sysUserBO.getStatus() == UserStatusEnum.DELETED.getCode()){
//            log.info("该用户被禁用");
//            throw new DisabledAccountException(ErrorCodeEnum.USER_IS_DISABLED.getErrorMsg());
//        }

        //账号判断 使用CredentialsMatcher进行密码匹配
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                sysUserBO,
                sysUserBO.getPassword(),
                ByteSource.Util.bytes(sysUserBO.getSalt()), //不加此参数则为明文登录
                getName()
        );

        return simpleAuthenticationInfo;
    }


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        log.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        SysUserDO userInfo  = (SysUserDO)principal.getPrimaryPrincipal();

        authorizationInfo.addStringPermission("user:add");
        return authorizationInfo;
    }


}
